<template>
	<view style="background-color: #f7f7f7;height: 100vh;">
		<view class="bg-top">
			<view class="userinfo">
				<view class="header">
					<image src="../../static/header.png" mode="widthFix"></image>
				</view>
				<view class="userinfo-content">
					<view class="">
						<view class="name" style="margin-bottom: 5rpx;">
							<text>{{user_name}}</text>
						</view>
					</view>
				</view>
			</view>
			<view @tap="path('/pages/index/set')" class="tn-icon-set" style="font-size: 50rpx;"></view>
		</view>
		<!-- 数据信息 -->
		<view class="tn-info__container tn-flex tn-flex-wrap tn-flex-col-center tn-flex-row-between tn-margin">
			<block v-for="(item, index) in tuniaoData" :key="index">
				<view @tap="path(item.path)"
					class="tn-info__item tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-between job-shadow">
					<view class="tn-info__item__left tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-left">
						<view
							class="tn-info__item__left--icon tn-flex tn-flex-col-center tn-flex-row-center tn-color-white"
							:class="[`tn-bg-${item.color}`]">
							<view :class="[`tn-icon-${item.icon}`]"></view>
						</view>
						<view class="tn-info__item__left__content">
							<view class="tn-info__item__left__content--title">{{ item.title }}</view>
						</view>
					</view>
					<view class="tn-info__item__right">
						<view class="tn-info__item__right--icon">
							<view class="tn-icon-right"></view>
						</view>
					</view>
				</view>
			</block>
		</view>

		<!-- 方式16 start-->
		<view v-if="status" class="tn-flex tn-flex-wrap tn-margin job-shadow">
			<block v-for="(item, index) in icons" :key="index">
				<view @tap="path(item.path)" class=" " style="width: 25%;">
					<view class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center  tn-padding-xl">
						<view class="icon16__item--icon tn-flex tn-flex-row-center tn-flex-col-center">
							<view class="tn-cool-color-icon16"
								:class="[$t.color.getRandomCoolBgClass(index) + ' tn-icon-' + item.icon]"></view>
						</view>
						<view class="tn-color-black tn-text-lg tn-text-center">
							<text class="tn-text-ellipsis">{{item.title}}</text>
						</view>
					</view>
				</view>
				<!-- 				<view v-if="!status && index == 4" @tap="path(item.path)" class=" " style="width: 25%;">
					<view class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center  tn-padding-xl">
						<view class="icon16__item--icon tn-flex tn-flex-row-center tn-flex-col-center">
							<view class="tn-cool-color-icon16"
								:class="[$t.color.getRandomCoolBgClass(index) + ' tn-icon-' + item.icon]"></view>
						</view>
						<view class="tn-color-black tn-text-lg tn-text-center">
							<text class="tn-text-ellipsis">{{item.title}}</text>
						</view>
					</view>
				</view> -->
			</block>
		</view>
		<!-- 		<view class="main-content">
			<view class="charts-box">
				<qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" />
			</view>
		</view> -->
		<tn-modal @tap='clickClose' v-model="showClose" title="提示" content="是否断开连接?" :button="button"></tn-modal>

		<tn-popup v-model="show" mode="bottom" :borderRadius="30">
			<view class="cu-dialog" @tap.stop="">
				<view class="cu-bar" style="margin-bottom: 20rpx;">
					<view class="content" style="color: #ecd2ac;">蓝牙设备</view>
					<tn-loading mode="circle" :show="true"></tn-loading>
				</view>
				<scroll-view class="v30">
					<view class="cu-list">
						<view @tap="connect(item)" class="cu-item" v-for="(item,index) in list" :key="index">
							<view class="content" v-if="item.name">{{item.name}}</view>
							<view class="content" v-if="item.name ==' '">
								无名称
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</tn-popup>
	</view>
</template>

<script>
	let _self,
		balance = null;
	import {
		debounce
	} from "@/common/debounce.js"

	export default {
		name: 'Basic',
		data() {
			return {
				status: false,
				tuniaoData: [{
						title: '预约取号',
						icon: 'clock',
						color: 'purplered',
						path: "/pages/index/Appointment"
					},
					{
						title: '面单打印',
						icon: 'receipt',
						color: 'green',
						path: "/pages/index/faceSheetPrinting"
					},
					{
						title: '包裹揽收',
						icon: 'cardbag',
						color: 'orange',
						path: "/pages/index/package"
					},
					{
						title: '称重揽收',
						icon: 'bluetooth',
						color: 'indigo',
						path: "/pages/index/packageWeight"
					}
				],
				icons: [{
						icon: "scan",
						title: "集包扫描",
						path: "/pages/index/collectionPackage"
					},
					{
						icon: "qr-barcode",
						title: "发运扫描",
						path: "/pages/index/packageCollection?type=3"
					},
					{
						icon: "cardbag-fill",
						title: "大件清关",
						path: "/pages/index/codeList"
					},
					{
						icon: "order-fill",
						title: "清关揽件",
						path: "/pages/index/solicitation"
					},
					// {
					// 	icon: "set",
					// 	title: "系统设置",
					// 	path: "/pages/index/set"
					// },
				],
				countTime: 0,
				// nav菜单列表               
				user_info: {},
				user_name: '',
				bluetoothStatus: '未连接',
				bluetoothInfo: {
					name: ''
				},
				show: false,
				list: [],
				showClose: false,
				button: [{
						text: '取消',
						backgroundColor: '#E6E6E6',
						fontColor: '#FFFFFF'
					},
					{
						text: '确定',
						backgroundColor: '#6f3e25',
						fontColor: '#FFFFFF'
					}
				],


				chartData: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['gauge'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: undefined,
					fontSize: 11,
					title: {
						name: '0.00kg',
						offsetY: 60
					},
					subtitle: {
						name: '重量',
						color: '#666666',
						offsetY: 60
					},
					extra: {
						// 仪表盘相关配置
						gauge: {
							type: 'default', // 仪表盘样式
							width: uni.upx2px(30), //仪表盘背景的宽度
							startAngle: 0.75, // 仪表盘起始角度
							endAngle: 0.25, // 仪表盘结束角度
							startNumber: 0, // 仪表盘起始数值
							endNumber: 75, // 仪表盘结束数值
							splitLine: {
								// 仪表盘刻度线配置
								fixRadius: 0, // 仪表盘刻度线径向偏移量
								splitNumber: 15, // 仪表盘刻度线分段总数量
								width: uni.upx2px(30), //仪表盘背景的宽度
								color: '#FFFFFF', // 仪表盘分割线颜色
								childNumber: 5, // 仪表盘子刻度线数量
								childWidth: uni.upx2px(30) * 0.4 //仪表盘背景的宽度
							},
							pointer: {
								// 仪表盘指针配置
								width: uni.upx2px(30) * 0.8, //指针宽度
								color: 'auto'
							}
						}
					},
				},
			}
		},
		watch: {
			// 监听蓝牙设备
			'$store.state.devicesList': {
				immediate: true,
				deep: true,
				handler(e) {
					if (e.length > 0) {
						this.list = e
					}
				}
			},
			show(e) {
				if (e) {
					this.$store.dispatch('startBluetoothDevicesDiscovery')
				} else {
					this.$store.dispatch('stopBluetoothDevicesDiscovery').then(res => {}).catch(err => {})
				}
			}
		},
		onLoad() {
			let self = this;
			uni.openBluetoothAdapter({
				success(res) {
					uni.startBluetoothDevicesDiscovery({
						services: ['FEE7'],
						success(res) {
							console.log(res)
						}
					})
				}
			})
			this.getRole()
			// this.getServerData()
			// #ifdef APP-PLUS
			//isPrimitive=false回调数据转成保留2位小数数据，isPrimitive=true蓝牙返回的原始数据流（已转成字符串）
			//经典蓝牙
			// bluetooth.initBluetooth({
			// 	isPrimitive: false
			// })
			//低功耗蓝牙秤
			// this.$store.commit('closeBluetoothAdapter')
			// this.$store.commit('openBluetoothAdapter')

			// if (uni.getStorageSync('deviceInfo')) {
			// 	this.connect(JSON.parse(uni.getStorageSync('deviceInfo')))
			// }
			// uni.onBLEConnectionStateChange(function(res) {
			// 	console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
			// 	if (!res.connected) {
			// 		self.bluetoothStatus = '未连接'
			// 	}
			// })
			// #endif

			if (uni.getStorageSync('user_name')) {
				this.user_name = uni.getStorageSync('user_name')
			}
			if (uni.getStorageSync('user_info')) {
				this.user_info = JSON.parse(uni.getStorageSync('user_info'))
			}
		},
		onShow() {
			// this.connectBluetooth()
			// this.printSomething()

		},
		methods: {
			//获取权限
			getRole() {
				this.$api.admin({
					apiUrl: '/differentiate',
					param: {}
				}).then((res) => {
					this.status = res.data.data.status
				}).catch((err) => {})
			},
			path(path) {
				uni.navigateTo({
					url: path
				})
			},
			getServerData() {
				//模拟从服务器获取数据时的延时
				setTimeout(() => {
					//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
					let res = {
						categories: [{
							"value": 0.2,
							"color": "#1890ff"
						}, {
							"value": 0.8,
							"color": "#2fc25b"
						}, {
							"value": 1,
							"color": "#f04864"
						}],
						series: [{
							name: "重量",
							data: 0
						}]
					};
					this.chartData = JSON.parse(JSON.stringify(res));
				}, 500);
			},
			getRandomCoolBg() {
				return this.$t.color.getRandomCoolBgClass()
			},
			showBlueTooth() {
				uni.vibrateShort()
				bluetooth.initBluetooth({
					isPrimitive: false
				})
				bluetooth.discoveryBluetooth((res) => { //多次回调，可添加到数组展示蓝牙列表
					console.log(res)
					//res数据：{"status":5,"data":{"name":"蓝牙名称","address":"蓝牙地址"}}
					if (res.status == 5 && res.data.name) {
						this.list = this.list.concat(res.data)
					}
				});
				this.show = true
			},
			closeConnet() {
				uni.vibrateShort()
				this.showClose = true

			},
			clickClose(e) {
				uni.vibrateShort()
				if (e.index == 0) {
					this.showClose = false
				} else {
					// this.$store.commit('closeBluetoothAdapter')
					// this.$store.commit('openBluetoothAdapter')
					bluetooth.disconnectBluetooth();
					this.bluetoothStatus = '未连接'
					this.showClose = false
				}
			},
			// 连接设备
			async connect(item) {
				let self = this;
				uni.vibrateShort()
				// try {
				// 	//链接蓝牙
				// 	await this.$store.dispatch('createBLEConnection', item)
				// 	this.bluetoothStatus = item.name
				// 	uni.setStorageSync('deviceInfo', JSON.stringify(item));
				// 	this.show = false
				// 	let characteristicId = await this.$store.dispatch('checkDeviceService', {
				// 		deviceId: item.deviceId,
				// 		serviceId: item.advertisServiceUUIDs[0]
				// 	})

				// 	this.notifyBLECharacteristicValueChange({
				// 		deviceId: item.deviceId,
				// 		serviceId: item.advertisServiceUUIDs[0],
				// 		characteristicId: characteristicId
				// 	})
				// } catch (err) {
				// 	console.log("错误", err)
				// }
			},
			// 监听重量
			async notifyBLECharacteristicValueChange(item) {
				let self = this;
				try {
					// 启用notify，必须先启用notify才能调用onBLECharacteristicValueChange
					await this.$store.dispatch('openNotify', {
						deviceId: item.deviceId,
						serviceId: item.serviceId,
						characteristicId: item.characteristicId
					})
					uni.onBLECharacteristicValueChange(function(res) {
						//监听蓝链接状态
						let weight = self.hexCharCodeToStr(self.ab2hex(res.value))
						weight = Number(weight.split("").reverse().join("").slice(0, 7)).toFixed(
							2);
						self.$store.commit('setWeight', weight)
					});
				} catch (err) {
					common.showToast('监听重量异常');
				}
			},
			setCharts(weight) {
				// uni.setScreenBrightness({
				// 	value: weight * 4 / 3 / 10,
				// 	success: function() {
				// 		console.log('success');
				// 	}
				// });
			},
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					alert("存在非法字符!");
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
		}
	}
</script>

<style lang="scss" scoped>
	/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
	.charts-box {
		width: 100%;
		height: 300px;
	}

	.main-content {
		margin-top: 500rpx;
		font-size: 40rpx;
	}

	.v30 {
		height: 30vh;

		.cu-item {
			text-align: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #ecd2ac;
			color: #666;
		}
	}

	.cu-dialog {
		padding: 40rpx;
	}

	.cu-bar {
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.content {
			margin-right: 10rpx;
			position: relative;
			top: -3rpx;
		}
	}

	.bg-top {
		background-color: #fff;
		width: 100%;
		padding: 40rpx;
		/* #ifdef APP-PLUS */
		padding-top: 130rpx;
		/* #endif */
		display: flex;
		justify-content: space-between;
		align-items: center;

		.userinfo {
			font-size: 30rpx;
			color: #333;
			display: flex;

			.header {
				margin-right: 20rpx;

				image {
					width: 110rpx;
				}
			}

			.userinfo-content {
				display: flex;
				align-items: center;
			}
		}

		.bluetooth {
			image {
				width: 30rpx;
			}

			display: flex;
			align-items: center;
			color: #333;
			font-size: 30rpx;
		}


	}

	/* 信息展示 start */
	.tn-info {

		&__container {
			margin-top: 30rpx;
		}

		&__item {
			width: 48%;
			margin: 15rpx 0rpx;
			padding: 38rpx 28rpx;
			border-radius: 10rpx;

			&__left {

				&--icon {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					font-size: 40rpx;
					margin-right: 20rpx;
					position: relative;
					z-index: 1;

					&::after {
						content: " ";
						position: absolute;
						z-index: -1;
						width: 100%;
						height: 100%;
						left: 0;
						bottom: 0;
						border-radius: inherit;
						opacity: 1;
						transform: scale(1, 1);
						background-size: 100% 100%;
						background-image: url(https://tnuiimage.tnkjapp.com/cool_bg_image/icon_bg3.png);
					}
				}

				&__content {
					font-size: 30rpx;

					&--data {
						margin-top: 5rpx;
						font-weight: bold;
					}
				}
			}

			&__right {
				&--icon {
					font-size: 30rpx;
					opacity: 0.5;
				}
			}
		}
	}

	.job-shadow {
		box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.07);
		border-radius: 20rpx;
	}

	/* 信息展示 end */

	/* 图标容器16 start */
	.tn-cool-color-icon16 {
		// background-image: -webkit-linear-gradient(135deg, #ED1C24, #FECE12);   16
		// background-image: linear-gradient(135deg, #ED1C24, #FECE12);
		-webkit-background-clip: text;
		background-clip: text;
		-webkit-text-fill-color: transparent;
		text-fill-color: transparent;
	}

	.icon16 {
		&__item {
			// width: 30%;
			background-color: #FFFFFF;
			border-radius: 10rpx;
			padding: 0rpx;
			margin: 0rpx;
			transform: scale(1);
			transition: transform 0.3s linear;
			transform-origin: center center;

			&--icon {
				width: 100rpx;
				height: 100rpx;
				font-size: 70rpx;
				border-radius: 50%;
				margin-bottom: 18rpx;
				position: relative;
				z-index: 1;
			}
		}
	}
</style>